import { showToast } from './../../utils/util'
var _typeof =
		'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator
			? function (t) {
					return typeof t
			  }
			: function (t) {
					return t &&
						'function' == typeof Symbol &&
						t.constructor === Symbol &&
						t !== Symbol.prototype
						? 'symbol'
						: typeof t
			  },
	app = getApp()

Page({
	data: {
		time: '',
		num: 1,
		see_price: !1,
		red_bag: 0,
		red_bag_id: 0,
		mode1: 'success',
		mode2: 'clear',
		mode3: 'clear',
		pay_mode: !1,
		refrer_to: '确认支付',
		pay_num: 1,
		type: 1,
		new_type: 0, //免费住传1
		present_time: '',
		lists: [
			{
				value: ''
			}
		]
	},
	onLoad(query) {
		this.initData(query)
		app.getUrl(this)
		app.getSystem(this)
		var s = 0
		var s2 = 0
		var s3 = 0
		var e = query.room_id,
			o = query.hotel_id,
			d = wx.getStorageSync('day1'),
			i = wx.getStorageSync('day2')
		var userId = app.globalData.userId
		app.util.request({
			url: 'entry/wxapp/GetRoomCost',
			data: {
				user_id: userId,
				room_id: e,
				start: d,
				end: i
			},
			success: t => {
				console.log(t.data, 'sss')
				for (var e in t.data.price_list) {
					s += Number(t.data.price_list[e].mprice)
					s2 += Number(t.data.price_list[e].xyprice) //协议价格
					s3 += Number(t.data.price_list[e].hyprice) //会议价格
				}
				this.setData({
					z_price: s,
					z_price2: s2,
					z_price3: s3,
					price_infos: t.data,
					use_coupon_num: t.data.can_use_coupon_num.price_can_use,
					settlement: s
				}),
					this.refresh(),
					this.room_num()
			}
		})
	},
	onShow() {
		this.userinfo(() => {
			;-1 != this.data.coupons_id ? this.cost() : '' == this.data.coupons_id && this.cost(),
				0 != this.data.red_bag && this.cost()
		})
	},
	/**
	 * @function 初始化数据
	 */
	initData(t) {
		var a = this
		// 获取当前时间
		var currentTime = new Date()
		// 设置为当前时间加上10分钟
		currentTime.setMinutes(currentTime.getMinutes() + 10)

		// 提取小时、分钟部分并赋值到新变量
		var hours = currentTime.getHours().toString().padStart(2, '0') // 使用 padStart() 函数来保持两位数形式
		var minutes = currentTime.getMinutes().toString().padStart(2, '0')

		// 构建最终结果字符串
		var result = `${hours}:${minutes}`
		a.setData({
			time: result,
			present_time: result
		})

		var e = t.room_id,
			o = t.hotel_id,
			d = wx.getStorageSync('day1'),
			i = wx.getStorageSync('day2'),
			r = wx.getStorageSync('day'),
			k = t.fx_x_user_id
		a.setData({
			room_id: e,
			hotel_id: o,
			day1: d,
			day2: i,
			day: r,
			coupon: 0,
			condition: 0,
			coupons_id: -1,
			form_d: t.form_d,
			grade: wx.getStorageSync('platform').open_member,
			fx_x_user_id: k,
			lists: [
				{
					value: wx.getStorageSync('userInfo').zs_name
				}
			]
		})
	},
	//免费住
	freeZhu: function (t) {
		var e = this.data
		if (e.new_type == 0) {
			this.setData({
				new_type: 1,
				settlement:
					(e.price_infos.free_rule.price.price + e.price_infos.free_rule.price.add_pay) *
					this.data.num
			})
		} else if (e.new_type == 1) {
			let settlement =
				e.price_infos.free_rule.price.price * this.data.num - 10 * this.data.use_coupon_num
			this.setData({
				new_type: 0,
				settlement: settlement
			})
		}
		// console.log('newType: '+e.new_type)
	},

	userinfo(cb) {
		var e = this
		app.getUserInfo(function (t) {
			e.setData(
				{
					userInfo: t
				},
				() => {
					cb()
				}
			)
		})
	},
	refresh: function (t) {
		var a = this,
			e = a.data.room_id,
			o = a.data.hotel_id
		2 == a.data.grade
			? (a.setData({
					discount: 1
			  }),
			  a.data.z_price)
			: app.getUserInfo(function (t) {
					t.id
					var e = t.discount
					null == e && (e = 10),
						a.setData({
							discount: e / 10,
							hbmoney: t.hbmoney //用户的红包总额
							//discount: 1
						}),
						null != a.data.z_price && a.cost()
			  })
		var d = app.globalData.userId
		app.util.request({
			url: 'entry/wxapp/MyCoupons',
			cachetime: '0',
			data: {
				user_id: d
			},
			success: function (t) {
				a.setData({
					coupons: t.data
				})
			}
		}),
			app.util.request({
				url: 'entry/wxapp/RoomDetails',
				cachetime: '0',
				data: {
					room_id: e
				},
				success: function (t) {
					t.data.price, t.data.yj_cost
					a.setData({
						room: t.data,
						yj_cost: Number(t.data.yj_cost)
					}),
						a.cost()
				}
			}),
			app.util.request({
				url: 'entry/wxapp/PjDetails',
				cachetime: '0',
				data: {
					seller_id: o
				},
				success: function (t) {
					a.setData({
						hotel: t.data,
						hotel_Name: t.data.name
					}),
						1 != t.data.wx_open && 1 != t.data.ye_open && a.mode2()
					wx.setNavigationBarTitle({
						title: t.data.name
					})
				}
			}),
			app.util.request({
				url: 'entry/wxapp/MyHb',
				cachetime: '0',
				data: {
					user_id: d,
					page: 1
				},
				success: function (t) {
					a.setData({
						my_hb: t.data
					})
				}
			})
	},
	room_num: function (t) {
		var d = this,
			e = wx.getStorageSync('day1'),
			a = wx.getStorageSync('day2'),
			o = d.data.room_id
		app.util.request({
			url: 'entry/wxapp/GetRoomNum',
			data: {
				room_id: o,
				start: e,
				end: a
			},
			success: function (t) {
				var e = [],
					a = []
				for (var o in (t.data.map(function (t) {
					var e
					;(e = Number(t.nums)), a.push(e)
				}),
				t.data))
					t.data[o].nums <= 0 && e.push(t.data[o])
				;(a = a.sort(app.sort_num_order)),
					d.setData({
						rooms: a[0]
					}),
					0 < e.length &&
						wx.showModal({
							title: '',
							content: e[0].dateday + '没有房间了',
							success: function (t) {
								t.confirm
									? wx.navigateBack({
											delta: 1
									  })
									: t.cancel &&
									  wx.navigateBack({
											delta: 1
									  })
							}
						})
			}
		})
	},
	use_res_bag: function (t) {
		wx.navigateTo({
			url: '../coupon/red_bag'
		})
	},
	bindTimeChange: function (t) {
		console.log(t, 'andjkhndashndjknjk')
		var e = t.detail.value,
			a = this.data.start + ' ' + e,
			o = this.data.rz_time,
			i = app.hours_time(a, o)
		//var e = t.detail.value, a = this.data.start + " " + e, o = this.data.rz_time, i = app.hours_time(a, 24);
		console.log(i)
		this.setData({
			time: t.detail.value,
			end_time: i
		})
		// this.setData({
		//     time: t.detail.value
		// });
	},
	/**
	 * @function 计算优惠券金额，这边是按照房间的总价来计算的
	 * @param {number} count 房间数量， 默认是1
	 */
	calculateCouponAmount(count = 1) {
		let totalPrice = this.data.price_infos.price_list.reduce((prev, cur) => {
			let curPrice = cur ? cur.mprice * 1 : 0
			return prev + curPrice
		}, 0)
		let use_coupon_num = Math.floor((totalPrice * count) / 100)
		console.log(
			`房型价格列表：${JSON.stringify(this.data.price_infos.price_list)}，房间售卖总价：${
				totalPrice * count
			}, 使用优惠券数量：${Math.floor((totalPrice * count) / 100)}`
		)
		// 判断优惠券是否用完
		return use_coupon_num < this.data.price_infos.user_have_coupon_num
			? use_coupon_num
			: this.data.price_infos.user_have_coupon_num
	},
	/**
	 * @function 新增房间
	 */
	add_num() {
		if (this.data.rooms == this.data.num) {
			showToast('房间数量不足，不能再添加啦')
		} else {
			let currentNum = this.data.num + 1
			let use_coupon_num = this.calculateCouponAmount(currentNum)

			// 入住人列表+1
			let lists = this.data.lists
			lists.push({
				value: ''
			})

			this.setData({
				lists: lists,
				num: currentNum,
				add_money: this.data.add_money * currentNum,
				use_coupon_num: use_coupon_num
			})
			console.log(`当前添加房间数：${currentNum}， 能用的优惠券数量：${use_coupon_num}`)
			this.cost()
		}
	},
	/**
	 * @function 删除房间
	 */
	reduce_num: function () {
		var currentNum = this.data.num - 1
		let use_coupon_num = this.calculateCouponAmount(currentNum)
		if (currentNum >= 1) {
			this.setData({
				num: currentNum,
				add_money: this.data.add_money * currentNum,
				use_coupon_num: use_coupon_num
			})
			this.cost()
		}

		var lists = this.data.lists
		if (lists.length > 1) {
			lists.pop()
			this.setData({
				lists: lists
			})
		}
	},
	see_price: function (t) {
		var e = this.data.see_price
		1 == e
			? this.setData({
					see_price: !1
			  })
			: this.setData({
					see_price: !0
			  })
	},
	mode1: function (t) {
		this.setData({
			mode1: 'success',
			mode2: 'clear',
			mode3: 'clear',
			refrer_to: '确认支付',
			type: 1
		}),
			this.refresh()
	},
	mode2: function (t) {
		this.setData({
			mode1: 'clear',
			mode2: 'success',
			mode3: 'clear',
			refrer_to: '确认支付',
			yj_cost: 0,
			type: 3
		}),
			this.cost()
	},
	/**
	 * @function 计算费用
	 * @param {*} t
	 */
	cost() {
		var e = this,
			a = e.data.num,
			o = Number(e.data.yj_cost),
			d = o * a,
			i = e.data.z_price,
			i2 = e.data.z_price2,
			i3 = e.data.z_price3,
			r = e.data.coupon,
			s = Number(e.data.red_bag)
		//识别协议客户
		if (e.data.userInfo && e.data.userInfo.xy_state && e.data.userInfo.xy_state == 1) {
			if (Number(a) >= 10) {
				//会议价格
				i = e.data.z_price
				var n = Number(i3) * a,
					c = n * e.data.discount,
					c1 = n * (1 - e.data.discount)
			} else {
				var n = Number(i2) * a,
					c = n * e.data.discount,
					c1 = n * (1 - e.data.discount)
			}
		} else {
			var n = Number(i) * a,
				c = n * e.data.discount,
				c1 = n * (1 - e.data.discount)
		}

		var u = n - c,
			p = c - r + d - s,
			m = n - r - s
		;(m = m.toFixed(2)) <= 0 && (m = 0), (c = c.toFixed(2)), (u = u.toFixed(2))
		var l = n
		;(p = p.toFixed(2)) <= 0 && (p = 0 != o ? d : 0.01),
			(n = (n += d).toFixed(2)),
			(l = l.toFixed(2)),
			console.log(n, l, p, c, u, m, d)
		var fangPrice = this.data.price_infos.free_rule.price.price * this.data.num
		// 如果用户有可用优惠券数量，并且不是权益房，则总房价减去优惠券的金额
		if (this.data.use_coupon_num > 0 && this.data.new_type != 1) {
			fangPrice = fangPrice - this.data.use_coupon_num * 10
		}
		var addPay = this.data.price_infos.free_rule.price.add_pay * this.data.num
		console.log(fangPrice + addPay, fangPrice)
		e.setData({
			price: n,
			total_price: l,
			settlement: this.data.new_type == 1 ? fangPrice + addPay : fangPrice,
			discount_price: c,
			reduction_price: u,
			dis_cost: m,
			yj_price: d
		})
	},
	use_coupon: function (t) {
		var e = this.data.discount_price,
			a = this.data.hotel_id
		wx.navigateTo({
			url: '../coupon/store_coupon?money=' + e + '&hotel_id=' + a
		})
	},
	pay_mode: function (t) {
		var e = this.data.pay_mode
		1 == e
			? this.setData({
					pay_mode: !1
			  })
			: this.setData({
					pay_mode: !0
			  })
	},
	formSubmit1: function (t) {
		var e = t.detail.formId
		this.setData({
			form_id: e
		})
	},
	bindRzrName: function (e) {
		var rownum = e.currentTarget.dataset.rownum
		var lists = this.data.lists
		lists[rownum].value = e.detail.value
		this.setData({
			lists: lists
		})

		console.log(this.data.lists, 'this.data.lists')
	},
	/**
	 * @function 检测form表单数据是否填写完善
	 */
	checkFormData() {
		// 名字不出现为空的情况；出现1个为空就是错的
		let isLiveNameError = this.data.lists.some(item => item.value === '')
		console.log(
			isLiveNameError,
			/^1\d{10}$/.test(this.data.userInfo.tel),
			this.data.userInfo.tel
		)
		if (isLiveNameError) {
			showToast('请填写入住人姓名')
			return false
		}
		return true
	},
	/**
	 * @function 提交订单
	 * @param {*} t
	 */
	formSubmit: function (t) {
		var that = this
		var e = this,
			a = e.data.form_d,
			o = e.data.form_id,
			that = this

		console.log('e.data.coupon')

		// 如果校验不通过，则不允许走下单链路
		if (!this.checkFormData()) {
			return false
		}

		var arr = that.data.lists
		// 使用 map() 函数遍历数组中的每个对象，并将其转换为字符串
		var strArr = arr.map(function (obj) {
			return obj.value ? obj.value.toString() : ''
		})

		// 使用 join() 函数将所有字符串连接起来
		var resultStr = strArr.join(',')
		console.log(resultStr, 'resultStr') // 输出 "1,2"

		var d = e.data.userInfo,
			i = t.detail.formId,
			r = e.data.hotel,
			s = e.data.room,
			n = t.detail.value.code,
			c = e.data.total_price,
			u = e.data.settlement,
			p = e.data.condition,
			// m = (e.data.price,
			//   t.detail.value.people),
			m = resultStr,
			l = t.detail.value.tel,
			_ = e.data.time,
			f = r.id,
			y = s.id,
			h = app.globalData.userId,
			g = e.data.coupons_id,
			x = r.name,
			w = r.address,
			v = r.coordinates,
			S = e.data.day1 + ' ' + _,
			b = e.data.day2,
			m2 = e.data.end_time,
			D = e.data.num,
			I = s.name,
			T = s.size,
			q = e.data.day,
			M = e.data.discount_price,
			j = e.data.yj_cost,
			z = e.data.coupon,
			N = s.logo,
			L = e.data.reduction_price,
			P = e.data.red_bag,
			k = e.data.red_bag_id,
			F = e.data.type,
			R = e.data.platform,
			O = '',
			fx = e.data.fx_x_user_id

		if ('' == m) O = '请填写入住人姓名'
		else if ('' == l) O = '请填写联系电话'
		else if (2 == R.is_sfz) n = ''
		else
			0 == /^1\d{10}$/.test(l)
				? (O = '请输入正确的手机号')
				: 0 < z
				? p > e.data.discount_price && (O = '不满足优惠券满减条件')
				: u <= 0 && (u = 0.01)
		var U = e.data.pay_num
		'' != O
			? (showToast(O),
			  e.setData({
					pay_num: 1
			  }))
			: '' == O &&
			  1 == U &&
			  (e.setData({
					pay_num: 0
			  }),
			  !app.globalData.hasRegister && 1 == e.data.garde
					? wx.showModal({
							content: '您需要注册会员',
							success: function (t) {
								t.confirm &&
									wx.navigateTo({
										url: '../register/register'
									})
							}
					  })
					: (wx.showLoading({
							title: '正在提交订单',
							mask: !0
					  }),
					  app.util.request({
							url: 'entry/wxapp/AddOrder',
							data: {
								name: m,
								tel: l,
								price: c,
								dd_time: _,
								seller_id: f,
								room_id: y,
								user_id: h,
								coupons_id: g,
								seller_name: x,
								seller_address: w,
								coordinates: v,
								arrival_time: S,
								departure_time: b,
								num: D,
								room_type: I,
								bed_type: T,
								days: q,
								dis_cost: M,
								yj_cost: j,
								yhq_cost: z,
								total_cost: u,
								room_logo: N,
								yyzk_cost: L,
								hb_id: k,
								hb_cost: P,
								from_id: o,
								classify: e.data.classify,
								type: F,
								qr_fromid: a,
								// code: n,
								add_money:
									e.data.price_infos.free_rule.price.add_pay * this.data.num, //就是额外付的钱
								new_type: e.data.new_type, //1免费住 0优惠券抵扣
								use_coupon_num: e.data.new_type == 1 ? 0 : this.data.use_coupon_num, //优惠券的数量,如果权益房，则不能用优惠券
								// fx_user_id:this.data.FID ? this.data.FID : 0
								fx_user_id: fx
							},
							method: 'POST',
							success: function (t) {
								var e = t.data,
									a = t.data
								console.log('下单结果', t)
								if (1 == F) {
									e = void 0 === e ? 'undefined' : _typeof(e)
									var o = app.OpenId
									'string' != e
										? app.util.request({
												url: 'check/subPay',
												cachetime: '0',
												data: {
													user_id: h,
													order_id: a
												},
												testapi: app.siteInfo.siteroot_web,
												success: function (t) {
													if (t.data.code === 0) {
														wx.openEmbeddedMiniProgram({
															appId: t.data.data.appId,
															path: t.data.data.prePayTn,
															envVersion: 'release',
															success: res => {
																// 订阅半屏小程序关闭，返回主体小程序事件
																app.globalData.eventObserver.subscribe(
																	'refreshOrderStatus',
																	res => {
																		that.getOrderStatus(a, res)
																		// 注销订阅
																		app.globalData.eventObserver.unSubscribe(
																			'refreshOrderStatus'
																		)
																	}
																)
																that.setData({
																	pay_num: 1
																})
															},
															fail: err => {
																showToast(
																	'打开支付半屏小程序失败，请先升级微信版本'
																)
															}
														})
													} else {
														showToast(t.data.msg)
														that.setData({
															pay_num: 1
														})
													}
												}
										  })
										: (showToast(t.data),
										  that.setData({
												pay_num: 1
										  }))
								} else if (2 == F) {
									e = void 0 === e ? 'undefined' : _typeof(e)
									o = app.OpenId
									'string' != e
										? app.util.request({
												url: 'entry/wxapp/YePay',
												cachetime: '0',
												data: {
													order_id: a
												},
												success: function (t) {
													wx.hideLoading(),
														wx.showToast({
															title: '支付成功'
														}),
														setTimeout(function () {
															wx.switchTab({
																url: '../order/order?activeIndex=0&index=0&status=0'
															})
														}, 1e3)
													var e = wx.getStorageSync('userInfo').openid
													app.util.request({
														url: 'entry/wxapp/Message',
														cachetime: '0',
														data: {
															form_id: i,
															openid: e,
															order_id: a
														},
														success: function (t) {}
													})
												}
										  })
										: wx.showModal({
												content: t.data
										  })
								} else
									3 == F &&
										(wx.hideLoading(),
										wx.showToast({
											title: '订单提交成功'
										}),
										setTimeout(function () {
											wx.switchTab({
												url: '../order/order?activeIndex=0&index=0&status=0'
											})
										}, 1500))
							}
					  })))
	},
	/**
	 * @function 获取订单状态
	 */
	getOrderStatus(id, res) {
		// 如果是从易宝小程序返回，表示小程序支付完成
		if (res.referrerInfo.appId !== app.globalData.payAppId) {
			return
		}
		wx.showLoading({
			title: '订单查询中...',
			mask: true
		})
		app.util.request({
			url: 'order/orderInfo',
			data: {
				id,
				user_id: app.globalData.userId
			},
			testapi: app.siteInfo.siteroot_web,
			success: res => {
				console.log('查询订单状态：', id, res)
				// 支付成功，跳转到订单详情
				if (res.data.data.order_status == 1) {
					wx.hideLoading()
					console.log(
						'支付成功：跳转路径',
						'../order/infoOrder?id=' + id + '&user_ids=' + app.globalData.userId
					)
					wx.reLaunch({
						url: '../order/infoOrder?id=' + id + '&user_ids=' + app.globalData.userId,
						fail: err => {
							console.log('跳转失败', err)
						}
					})
				} else {
					showToast('支付失败')
				}
			}
		})
	}
})
